import React, {Component, useState, useEffect, useRef} from 'react';
import {View, Text, StyleSheet, Platform, TextInput, Button, ScrollView, Dimensions, FlatList, Alert, TouchableHighlight, StatusBar, Image} from 'react-native';

import image_list from './image_list';

const ScreenWidth = Dimensions.get('window').width;

const Advertisements = [
  {title: '广告1', src: image_list.img1},
  {title: '广告2', src: image_list.img2},
  {title: '广告3', src: image_list.img3},
  {title: '广告**', src: image_list.img3}
];

//指示器
const circleSize = 8;
const circleMargin = 5;

// 样式
const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column'
  },
  search_bar: {
    marginTop: Platform.OS == 'android' ? 0 : 20,
    height: 40,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    padding: 2
  },
  input: {
    flex: 1,
    borderColor: 'gray',
    borderWidth: 2,
    borderRadius: 10
  },
  button:{
    flex: 1
  },
  ad_banner: {
    height: 180,
    justifyContent: 'center',
    alignItems: 'flex-start',
    backgroundColor: 'green'
  },
  product_list: {
    flex: 1,
    justifyContent: 'center'
  },
  product_item: {
    padding: 10,
    fontSize: 18,
    height: 44,
    justifyContent: 'flex-start',
    flexDirection: 'row',
    alignItems: 'center'
  },
  product_img: {
    height: 40,
    width: 40,
    borderWidth: 0.5,
    borderColor: 'gray'
  },
  advContent: {
    width: ScreenWidth,
    height: 180
  },
  indicator: {
    width: ScreenWidth,
    height: 20,
    backgroundColor: 'rgba(0,0,0,0)',
    alignItems: 'center',
    justifyContent: 'center',
    top: 150,
    position: 'absolute',
    flexDirection: 'row'
  }
});

class StatusBarComponent extends React.Component {
  render() {
    return (
      <View>
        <StatusBar 
        backgroundColor={'blue'}
        barStyle={'default'}
        networkActivityIndicatorVisible={true}
        ></StatusBar>
      </View>
    );
  }
}

class ComponentAdBanner extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      currentPage: 0
    };
  }

  render() {
    return (
      <View style={styles.ad_banner}>
        <ScrollView 
          horizontal={true}
          pagingEnabled={true}
          showsHorizontalScrollIndicator={false}
          ref={ com => {this._scrollView = com}}>
            <TouchableHighlight 
              onPress={() => {
                Alert.alert('点击banner', null, null);
              }}>
              <Text style={{width: ScreenWidth, height: 180, backgroundColor: 'green'}}>广告1</Text>
            </TouchableHighlight>
            <TouchableHighlight>
              <Text style={{width: ScreenWidth, height: 180, backgroundColor: 'gray'}}>广告2</Text>
            </TouchableHighlight><TouchableHighlight>
              <Text style={{width: ScreenWidth, height: 180, backgroundColor: 'yellow'}}>广告3</Text>
            </TouchableHighlight>
        </ScrollView>
      </View>
    ); 
  }

  componentDidMount() {
    this._startTimer();
  }

  componentWillUnmount() {
    clearInterval(this.interval);
  }

  _startTimer() {
    this.interval = setInterval(() => {
      var nextPage = this.state.currentPage + 1;
      if (nextPage >= 3) {
        nextPage = 0;
      }
      this.setState({currentPage: nextPage});
      const offSetX = nextPage * ScreenWidth;
      this._scrollView.scrollTo({x: offSetX, y: 0, animated: true});
    }, 2000);
  }
}

const AdBanner = () => {
  const [pageNumber, setPageNumber] = useState(0);
  const countRef = useRef(pageNumber);

  useEffect(() => {
    countRef.current = pageNumber;
  })

  useEffect(() => {
    let interval = setInterval(() => {
      var nextPage = countRef.current + 1;
      if (nextPage >= 3) {
        nextPage = 0;
      }
      setPageNumber(nextPage);
      const offSetX = nextPage * ScreenWidth;
      this._banner.scrollTo({x: offSetX, y: 0, animated: true});
    }, 3000);
    return () => {
      clearInterval(interval);
      interval = null;
    }
  }, [])

  return (
    <View style={styles.ad_banner}>
        <ScrollView 
        horizontal={true}
        pagingEnabled={true}
        showsHorizontalScrollIndicator={false}
        ref = {com => this._banner = com}
        >
          {Advertisements.map((adv, index) => {
            return (
              <TouchableHighlight key={index} onPress={() => Alert.alert('点击banner:' + index, null, null)}>
                <Image style={styles.advContent} source={adv.src}/>
              </TouchableHighlight>
            );
          })}
        </ScrollView>
        <View style={[styles.indicator]}>
          {Advertisements.map((_, index) => {
            return (
              <Text key={index} style={[(index === pageNumber) ? {color: 'orange'} : {color: 'white'}, {fontSize: 24}]}>
                 • 
              </Text>
            );
          })}
        </View>
      </View>
  );
};

const SearchBar = () => {
  const [searchText, setSearchText] = useState('');

  return (
    <View style={styles.search_bar}>
      <TextInput style={styles.input} placeholder="搜索" onChangeText={(text) => {
        setSearchText(text);
      }}>{searchText}</TextInput>
      <Button onPress={() => {
        Alert.alert("输入内容：" + searchText, null, null);
      }} title="搜索"></Button>
    </View>
  );
}

const Products = () => {
  const [refreshing, setRefreshing] = useState(false)

  var data = [];
  for (var i = 0; i < 20; i++) {
    data.push({key: i, title: "商品" + i, desc: "这是描述信息"});
  }

  _renderImte = (item) => {
    return (
      <View style={styles.product_item}>
        <Image style={styles.product_img} source={require('./images/product_icon.png')}/>
        <View>
          <Text >{item.title}</Text>
          <Text >{item.desc}</Text>
        </View>
      </View>
    );
  };

  _seperateLine = () => {
    return (
      <View style={{height: 1, backgroundColor: 'purple'}}></View>
    );
  };

  _loadData = () => {
    setRefreshing(true);
    setTimeout(() => {
      Alert.alert("刷新完成", null, null);
      setRefreshing(false);
    }, 2000);
  };

  return (
    <View style={styles.product_list}>
      <FlatList 
        style={{flex: 1}}
        data={data}
        renderItem={({item}) => this._renderImte(item)}
        ItemSeparatorComponent={this._seperateLine}
        refreshing={refreshing}
        onRefresh={
          this._loadData
        }/>
    </View>
  );
}

// 布局
const TaobaoPage = () => {
  return (
    <View style={styles.container}>
      <StatusBarComponent />
      <SearchBar />
      <AdBanner/>
      <Products />
    </View>
    
  );
};

export default TaobaoPage;